<template>
  <div class="container">
    <!-- 搜索框 -->
    <div class="handle-box">
      <el-input class="handle-input" v-model="search_text" placeholder="请输入视频名关键字" size="mini" prefix-icon="el-icon-search" clearable />
      <el-button type="primary" size="mini" @click="addDialogVisiable = true">添加视频</el-button>
      <el-button type="primary" size="mini" @click="changeHotVideo()">修改热门视频</el-button>
    </div>
    <!-- 视频卡片 -->
    <div class="card-container" @click="handlePlay($event)">
      <div v-if="data.length == 0">暂无视频信息</div>
      <el-card v-for="item of data" :key="item.id" shadow="hover" class="video-card" :body-style="{ padding: '0px'}">
        <div class="card-hover">
          <el-button type="primary" size="small" @click="handleEdit(item)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(item.id)">删除</el-button>
        </div>
        <img class="img-pic" id="a" :videoName="item.videoName" :url="item.url" :src="getUrl(item.pic)">
        <div class="content-wrapper">
          <span class="card-title" :videoName="item.videoName" :url="item.url">{{item.videoName}}</span>
          <i class="iconfont icon-avatar1"> {{item.authorName}}</i>
          <i class="iconfont icon-play1"> {{item.playNumber}}</i>
          <i class="iconfont icon-clock1"> {{attachDate(item.createTime)}}</i>
          <i class="iconfont icon-good"> {{item.praise}}</i>
        </div>
      </el-card>
    </div>
    <!-- 翻页 -->
    <div class="pagination">
      <el-pagination background class="page"
      layout="total,prev,pager,next"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="tableData.length"
      @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <!-- 添加视频框 -->
    <el-dialog title="添加新视频" :visible.sync="addDialogVisiable" center width="400px">
      <el-form :model="registerForm" id="add-form" ref="registerForm" :rules="rules" label-width="80px" :inline="false" size="small" enctype="multipart/form-data">
        <el-form-item prop="authorId" label="作者ID" size="mini">
          <el-input v-model="registerForm.authorId" name="authorId" placeholder="作者ID"></el-input>
        </el-form-item>
        <el-form-item prop="videoName" label="视频名字" size="mini">
          <el-input v-model="registerForm.videoName" maxlength="30" name="videoName" placeholder="视频名字"></el-input>
        </el-form-item>
        <el-form-item prop="style" label="视频风格" size="mini">
          <el-select v-model="registerForm.style" name="style" placeholder="请选择">
            <el-option
              v-for="item in videoStyles"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="introduction" label="视频简介" size="mini">
          <el-input v-model="registerForm.introduction" maxlength="10000" name="introduction" type="textarea" placeholder="视频简介"></el-input>
        </el-form-item>
        <el-form-item prop="url" accept="video/*" label="视频内容" size="mini">
          <input type="file" @change="previewVideo()" name="file" id="new_video_url" >
        </el-form-item>
        <el-form-item prop="pic" accept="image/*" label="视频封面" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <div class="video-wrap">
        <video :src="video0Url" style="height:200px" id="video0"></video>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="addVideo">确定</el-button>
        <el-button @click="addDialogVisiable = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 修改视频框 -->
    <el-dialog title="修改视频" :visible.sync="editVisiable" center width="400px">
      <el-form :model="form" id="edit-form" ref="form" :rules="rules" label-width="80px" :inline="false" size="small">
        <el-form-item prop="authorId" label="作者ID" size="mini">
          <el-input v-model="form.authorId" name="authorId" placeholder="作者ID"></el-input>
        </el-form-item>
        <el-form-item prop="videoName" label="视频名字" size="mini">
          <el-input v-model="form.videoName" maxlength="30" name="videoName" placeholder="视频名字"></el-input>
        </el-form-item>
        <el-form-item prop="style" label="视频风格" size="mini">
          <el-select v-model="form.style" name="style" placeholder="请选择">
            <el-option
              v-for="item in videoStyles"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="introduction" label="视频简介" size="mini">
          <el-input v-model="form.introduction" maxlength="10000" name="introduction" type="textarea" placeholder="视频简介"></el-input>
        </el-form-item>
        <el-form-item prop="url" accept="video/*" label="视频内容" size="mini">
          <input type="file" @change="previewVideo2()" name="file" id="edit_video_url" >
        </el-form-item>
        <el-form-item prop="pic" accept="image/*" label="视频封面" size="mini">
          <input type="file" name="file" id="video_pic">
        </el-form-item>
      </el-form>
      <div class="video-wrap">
        <video :src="video1Url" style="height:200px" id="video1"></video>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="editVideo">确定</el-button>
        <el-button @click="editVisiable = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 删除框 -->
    <el-dialog title="删除视频" :visible.sync="delVisible" center width="300px">
      <div align="center">删除不可恢复，是否确定删除？</div>
      <span slot="footer">
        <el-button type="primary" @click="deleteRow">确定</el-button>
        <el-button @click="delVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 修改热门视频 -->
    <el-dialog title="修改热门视频(输入视频id)" :visible.sync="hotVideoDialogVisiable" center width="400px">
      <div class="hot-video">
        <input v-for="index in 10" :key="index" v-model="hotVideo[index-1]" :placeholder="'热门视频'+index"/>
      </div>

      <span slot="footer">
        <el-button type="primary" @click="updateHotVideo()">确定</el-button>
        <el-button @click="hotVideoDialogVisiable = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getAllVideo, setVideo,delVideo, updateVideo,getAllHotVideo,updateHotVideo} from '../api/index'
import {videoStyles} from '../assets/data/videoStyles'
import {mixin} from '../mixins/index'
export default {
  mixins:[mixin],
  data(){
    return {
      idx:-1,     //记录当前选中的行
      search_text:'',  //筛选的关键字
      addDialogVisiable:false,  //添加视频框
      video0Url:'',
      video1Url:'',
      videoDuration:'',
      videoStyles:[],    //视频风格
      delVisible:false,  //删除提示框
      editVisiable:false,  //编辑框
      hotVideoDialogVisiable:false,  //热门视频id框
      hotVideo:[],    //10个热门视频id
      tableData:[],   //显示的视频信息
      tempData:[],    //暂存的视频信息
      currentPage:1,  //当前页
      pageSize:12,    //每一页个数
      registerForm:{  //添加新视频表
        authorId:'000000',
        videoName:'',
        style:'',
        introduction:'',
      },
      form:{  //修改视频表
        id:-1,
        authorId:'',
        videoName:'',
        style:'',
        introduction:'',
      },
      rules:{         //添加视频规则
        authorId:[
          {required:true,message:'请输入作者ID',trigger:'blur'}
        ],
        videoName:[
          {required:true,message:'请输入视频名字',trigger:'blur'}
        ],
        style:[
          {required:true,message:'请选择视频风格',trigger:'blur'},
        ],
        introduction:[
          {required:false,message:'请输入视频简介',trigger:'blur'},
        ],
      }
    }
  },
  watch:{
    search_text:function(){
      this.currentPage = 1
      if(this.search_text == ''){
        this.tableData = this.tempData
      }else{
        this.tableData = []
        for(let item of this.tempData){
          if(item.videoName.includes(this.search_text)){
            this.tableData.push(item)
          }
        }
      }
    }
  },
  computed:{
    data(){
      return this.tableData.slice((this.currentPage-1)*this.pageSize,this.currentPage*this.pageSize)
    }
  },
  created(){
    this.getData();
  },
  mounted(){
    this.videoStyles = videoStyles
  },
  methods:{
    //修改热门视频
    changeHotVideo(){
      getAllHotVideo()
        .then(res =>{
          this.hotVideo = res
        })
      this.hotVideoDialogVisiable = true
    },
    updateHotVideo(){
      var params = new URLSearchParams()
      for(let item in this.hotVideo){
        params.append('videoId',this.hotVideo[item])
      }
      updateHotVideo(params)
        .then(() =>{
          this.notify('修改成功','success')
        }).catch(()=>{
          this.notify('修改失败','warning')
        })
    },
    handlePlay(e){
      var attr = e.target.attributes;
      if(attr.url){
        this.playVideo(attr.videoName.value,attr.url.value)
      }
    },
    //播放界面
    playVideo(videoName,url){
      this.$store.commit('setPlayFrame',true)
      this.$store.commit('setUrl',url)
      this.$store.commit('setIsPlay',false)
      this.$store.commit('setVideoName',videoName)
    },
    //获取当前页
    handleCurrentChange(val){
      this.currentPage = val;
    },
    //查询所有视频
    getData(){
      this.tempData=[]
      this.tableData=[]
      getAllVideo()
        .then(res =>{
          this.tempData = res
          this.tableData = res
          this.currentPage = 1
        }).catch(err =>{
          console.log(err);
        })
    },
    previewVideo(){
      var video = document.getElementById("new_video_url");
      try {
        var objURL = this.getObjectURL(video.files[0]);
      } catch (err) {
        this.video0Url = ''
        this.videoDuration = ''
        return 
      }
      const isVideo = (video.files[0].type === 'video/mp4')
      if(isVideo){
        this.video0Url = objURL
      }else{
        this.video0Url = ''
      }
      var video0 = document.getElementById("video0");
      setTimeout(() => {
        this.videoDuration = video0.duration
      }, 100);
    },
    previewVideo2(){
      var video = document.getElementById("edit_video_url");
      try {
        var objURL = this.getObjectURL(video.files[0]);
      } catch (err) {
        this.video0Url = ''
        this.videoDuration = ''
        return 
      }
      const isVideo = (video.files[0].type === 'video/mp4')
      if(isVideo){
        this.video1Url = objURL
      }else{
        this.video1Url = ''
      }
      var video1 = document.getElementById("video1");
      setTimeout(() => {
        this.videoDuration = video1.duration
      }, 100);
    },
    //编辑视频信息
    handleEdit(row){
      this.form = []
      this.form = {
        id:row.id,
        authorId:row.authorId,
        videoName:row.videoName,
        style:row.style,
        introduction:row.introduction,
      }
      this.editVisiable = true;
    },
    editVideo(){
      this.$refs['form'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("edit-form"));
          formData.append('id',this.form.id)
          formData.append('duration',parseInt(this.videoDuration))
          updateVideo(formData)
            .then(res =>{
              if(res.code==1){
                this.getData();
                this.notify('修改成功','success')
              }else{
                this.notify('修改失败','error')
              }
            }).catch(err => {
            console.log(err)
          })
          this.editVisible = false;
        }
      })
    },
    //删除视频
    deleteRow(){
      delVideo(this.idx)
        .then(res =>{
          if (res) {
            this.getData();
            this.notify('删除成功','success')
          }else{
            this.notify('删除失败','error')
          }
        })
      this.delVisible = false
    },
    //点击确定后添加视频
    addVideo(){
      this.$refs['registerForm'].validate(valid =>{
        if(valid){
          var formData = new FormData(document.getElementById("add-form"));
          formData.append('duration',parseInt(this.videoDuration))

          setVideo(formData)
          .then(res =>{
            if(res.code == 1){
              this.getData();
              this.notify("添加成功","success")
            }else{
              this.notify(res.msg,"error")
            }
          }).catch(err => {
            console.log(err)
          })
          this.addDialogVisible = false;
        }
      })
    },
    getObjectURL(file) {
        var url = null;
        if (window.createObjectURL) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
  }
}
</script>

<style scoped>
@import '../assets/css/videoPage.css';
</style>